package http;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


import outils.PropertyLoader;
import transfert.objects.CreateSeanceRequest;
import transfert.objects.SeanceType;


public class Client implements Runnable {

	private PropertyLoader pl = null;
	private static Client instance = null;
	private String propertyFile = null;
	private Boolean running = true;
	private Object object = null;

	private Client(){			
		Thread thread = new Thread(this);
		thread.start();		
	}

	public String getPropertyFile() {
		return propertyFile;
	}

	public void setPropertyFile(String propertyFile) {
		this.propertyFile = propertyFile;
	}

	public synchronized void setObject(Object object)
	{
		this.object = object;
	}

	public void appelHttp(){
		try {

			pl = new PropertyLoader(propertyFile);
			URL url = new URL(pl.getString("urlServiceHttp"));
			System.out.println("url=" + pl.getString("urlServiceHttp"));
			URLConnection connection = url.openConnection();

			connection.setReadTimeout(5000);
			/*
			 * 		connection.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
			 */		
			HttpURLConnection http = (HttpURLConnection) connection;
			http.setRequestMethod("POST");
			http.setDoInput(true);
			http.setDoOutput(true);

			/*	
			 * http.setUseCaches(false);
			 */
			/*InputStream is = http.getInputStream();*/

			OutputStream os = http.getOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(os);
			oos.writeObject(object);
			oos.flush();
			System.out.println("o=" + object);
			int status = http.getResponseCode();

			if (status != HttpURLConnection.HTTP_OK) {
				System.out.println("Status : " +status);
			}
			this.setObject(null);
			/*is.read();*/
			/*oos.close();*/
			/*	
			ObjectInputStream ois = new ObjectInputStream(http.getInputStream());
		    Object oi = ois.readObject();
		    ois.close();*/

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}/* catch (ClassNotFoundException e){
			e.printStackTrace();
		}*/
	}


	public static Client getInstance(){
		if(instance == null){
			instance = new Client();
		}
		return instance;		
	}

	@Override
	public void run() {
		while(running){
			synchronized (object) {
				if (object == null){
					continue;
				}
					System.out.println("lancer requete");
					this.appelHttp();
					System.out.println("apres requete");
					//Thread.sleep(10000);
		
			}
		}

	}

	/*	public static void main(String[] args) {
		Client client = Client.getInstance();
		client.setPropertyFile("PM.properties");		
	}*/


}
